let layer
layui.use(function () {
    let $ = layui.$;
    let form = layui.form;
    layer = layui.layer;
    let util = layui.util;


    // 自定义验证规则
    form.verify({
        // 确认密码
        confirmPassword: function (value, item) {
            var passwordValue = $('#reg-password').val();
            if (value !== passwordValue) {
                return '两次密码输入不一致';
            }
        }
    });

    // 提交事件
    form.on('submit(demo-reg)', function (data) {
        var field = data.field; // 获取表单字段值

        // 是否勾选同意
        if (!field.agreement) {
            layer.msg('您必须勾选同意用户协议才能注册');
            return false;
        }

        // 显示填写结果，仅作演示用
        layer.alert(JSON.stringify(field), {
            title: '当前填写的字段值'
        });

        // 此处可执行 Ajax 等操作
        // …

        return false; // 阻止默认 form 跳转
    });

    // 普通事件 标签里面有 lay-on 属性的标签绑定事件 lay-on 的属性值
    // 比如绑定的是 lay-on="send-code"
    // util.on('lay-on', {
    //     // 获取验证码
    //     'send-code': function () {
    //
    // });
});

let username = document.querySelector("[name='username']")
username.onblur = () => {
    // TODO 用户名校验
    let name = username.value
    let xhr = new XMLHttpRequest()
    xhr.open("get","/get?username=" + name, true)
    xhr.send()
    xhr.onreadystatechange = () => {
        if (xhr.readyState === 4 && xhr.status === 200) {
            console.log(xhr.responseText)
            let resp = JSON.parse(xhr.responseText)
            layer.msg(resp.msg)
        }
    }
}
let phone = document.querySelector("[name='phone']")

document.querySelector("#send").onclick = () => {
    console.log("发送验证码")
    // TODO 发送验证码
    let p = phone.value
    let xhr = new XMLHttpRequest()
    xhr.open("get", "/send?phone=" + p, true)
    xhr.send()
    xhr.onreadystatechange = () => {
        if (xhr.readyState === 4 && xhr.status === 200) {
            let res = JSON.parse(xhr.responseText)
            layer.msg(res.msg)
        }
    }
}
let code = document.querySelector("[name='code']")
code.onblur = () => {
    let c = code.value
    let xhr = new XMLHttpRequest()
    xhr.open("get", "/verify?phone=" + phone.value + "&code=" + c, true)
    xhr.send()
    xhr.onreadystatechange = () => {
        if (xhr.readyState === 4 && xhr.status === 200) {
            let res = JSON.parse(xhr.responseText)
            layer.msg(res.msg)
        }
    }
}
